﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;

namespace easysql
{
    public abstract class ConnPool
    {
        private String _connString;
        private int _minIdleConnections = 1;//空闲池,最小连接池
        private int _maxIdleConnections = 10;//空闲池,最大连接数
        private int _maxActiveConnections = 100;//最大允许的连接数量

        //空闲连接
        public Queue<DbConnection> idleConnections = new Queue<DbConnection>();

        //活动连接(正在使用的连接)
        public List<DbConnection> activeConnections = new List<DbConnection>();

        //private ThreadLocal<DbConnection> threadLocal = new ThreadLocal<DbConnection>();



        public ConnPool(String connString)
        {
            this._connString = connString;
        }
        public ConnPool(String connString,int minIdleConnections,int maxIdleConnections,int maxActiveConnections)
        {
            this._connString = connString;
            this._minIdleConnections = minIdleConnections;
            this._maxIdleConnections = maxIdleConnections;
            this._maxActiveConnections = maxActiveConnections;
        }

        public DbConnection getConn()
        {
            DbConnection conn = null;
            
            if(idleConnections.Count == 0)
            {
                conn = this.createConn(this._connString);
            }
            else
            {
                conn = idleConnections.Dequeue();
            }
            this.activeConnections.Add(conn);
            return conn;
        }


        protected abstract DbConnection createConn(String connString);


        //释放连接
        public void releaseConn(DbConnection conn)
        {
            activeConnections.Remove(conn);
            if(conn!=null && conn.State != System.Data.ConnectionState.Closed)
            {
                this.idleConnections.Enqueue(conn);
            }
        }
        // 判断连接是否可用
        private bool isValid(DbConnection conn)
        {
            if (conn == null || conn.State == System.Data.ConnectionState.Closed ||conn.State == System.Data.ConnectionState.Broken)
            {
                return false;
            }
            return true;
        }





    }
}
